//
//  ResultViewController.m
//  YiQiTingShu
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 直到世界的尽头. All rights reserved.
//

#import "ResultViewController.h"
#import "PublicHeader.h"
#import "FPlayViewController.h"
#import "FTableViewCell.h"
#import "WWContentTableCell.h"
#import "WWTableContentModel.h"
#import "FAlbumDetail.h"
#import <MJExtension.h>
#import <UIImageView+WebCache.h>
#import "FSearchMusicModel.h"
#import "FSearchAlbumModel.h"
#import "AlbumFViewController.h"
#import <MBProgressHUD.h>

#define ALLURLString @"http://search.ximalaya.com/front/v1?core=all&device=iPhone&kw=%@&page=1&rows=3"
#define AlbumURLString @"http://search.ximalaya.com/front/v1?condition=%@&core=album&device=iPhone&kw=%@&page=1&rows=20"
#define MusicURLString @"http://search.ximalaya.com/front/v1?condition=%@&core=track&device=iPhone&kw=%@&page=1&rows=20"

@interface ResultViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@property(nonatomic, strong)NSMutableArray *albumArray;
@property(nonatomic, strong)NSMutableArray *musicArray;
@property(nonatomic, strong)UISegmentedControl *segmentedControl;
@property(nonatomic, assign)BOOL isFirst;
@property(nonatomic, strong)UISegmentedControl *typeSegmentControl;
@property(nonatomic, strong)NSArray *typeArray;
@property(nonatomic, assign)BOOL isAlbum;
@property(nonatomic, strong)NSString *urlString;
@property(nonatomic, strong)MBProgressHUD *progressView;
@end

@implementation ResultViewController

#pragma mark - 懒加载
#pragma mark 加载图
-(MBProgressHUD *)progressView
{
    if (!_progressView) {
        _progressView = [[MBProgressHUD alloc]initWithView:self.view];
        _progressView.labelText = @"加载中";
        [_progressView setMode:MBProgressHUDModeIndeterminate];
        [_progressView show:YES];
        [_progressView NightWithType:UIViewColorTypeNormal];
    }
    return _progressView;
}
#pragma mark 上面的segment
-(UISegmentedControl *)segmentedControl
{
    if (!_segmentedControl) {
        _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"全部", @"找专辑", @"找声音"]];
        _segmentedControl.frame = CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(35));
        _segmentedControl.tintColor = [UIColor orangeColor];
        [_segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateNormal];
        [_segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _segmentedControl;
}

#pragma mark 下面的segment
-(UISegmentedControl *)typeSegmentControl
{
    
    if (!_typeSegmentControl) {
        _typeSegmentControl = [[UISegmentedControl alloc] initWithItems:@[@"相关度", @"最新上传", @"最多播放"]];
        _typeSegmentControl.frame = CGRectMake(FitConstant_XorWidth(30), _segmentedControl.frame.origin.y + _segmentedControl.frame.size.height + FitConstant_YorHeight(5), self.view.frame.size.width - FitConstant_XorWidth(60), FitConstant_YorHeight(30));
        _typeSegmentControl.tintColor = [UIColor colorWithRed:0.96 green:0.4 blue:0.26 alpha:1];
        [_typeSegmentControl addTarget:self action:@selector(typeAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _typeSegmentControl;
}

#pragma mark 上方分类的segment
-(void)segmentedControlAction:(UISegmentedControl *)segmented
{
    [self.view addSubview:_progressView];
    switch (segmented.selectedSegmentIndex) {
        case 0:
            [self.typeSegmentControl removeFromSuperview];
            self.tableView.frame = CGRectMake(0, FitConstant_YorHeight(35), self.view.frame.size.width, ScreenHeight - 64 - _segmentedControl.frame.size.height - _segmentedControl.frame.size.height);
            if (_dataSource.count == 0) {
                [self initData];
            }
            else{
                [_progressView removeFromSuperview];
                [self.tableView reloadData];
            }
            break;
        case 1:
            _typeSegmentControl.selectedSegmentIndex = 0;
            [self.view addSubview:self.typeSegmentControl];
            self.tableView.frame = CGRectMake(0, FitConstant_YorHeight(75), self.view.frame.size.width, ScreenHeight - 64 - _typeSegmentControl.frame.size.height - _typeSegmentControl.frame.size.height);
            _urlString = AlbumURLString;
            if (_albumArray.count == 0) {
                [self initAlbumData:_typeArray[0]];
            }
            else{
                [_progressView removeFromSuperview];
                [self.tableView reloadData];
            }
            break;
        case 2:
            _typeSegmentControl.selectedSegmentIndex = 0;
            [self.view addSubview:self.typeSegmentControl];
            self.tableView.frame = CGRectMake(0, FitConstant_YorHeight(75), self.view.frame.size.width, ScreenHeight - 64 - _typeSegmentControl.frame.size.height - _typeSegmentControl.frame.size.height);
            _urlString = MusicURLString;
            if (_musicArray.count == 0) {
                [self initMusicData:_typeArray[0]];
            }
            else{
                [_progressView removeFromSuperview];
                [self.tableView reloadData];
            }
            
            break;
            
        default:
            break;
    }
}

#pragma mark 下方分类的segment
-(void)typeAction:(UISegmentedControl *)segmented
{
    [self.view addSubview:_progressView];
    if (_segmentedControl.selectedSegmentIndex == 1) {
        _urlString = AlbumURLString;
        switch (segmented.selectedSegmentIndex) {
            case 0:
                [self initAlbumData:_typeArray[0]];
              
                break;
            case 1:
                [self initAlbumData:_typeArray[1]];
                
                break;
            case 2:
                [self initAlbumData:_typeArray[2]];
                
                break;
                
            default:
                break;
        }
    }
    else {
        _urlString = MusicURLString;
        switch (segmented.selectedSegmentIndex) {
            case 0:
                [self initMusicData:_typeArray[0]];
                
                break;
            case 1:
                [self initMusicData:_typeArray[1]];
                
                break;
            case 2:
                [self initMusicData:_typeArray[2]];
               
                break;
                
            default:
                break;
        }
    }
    
}

#pragma mark tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _segmentedControl.frame.origin.y + _segmentedControl.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - _segmentedControl.frame.size.height - _segmentedControl.frame.origin.y - FitConstant_XorWidth(40)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

#pragma mark - 界面初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _typeArray = @[@"relation", @"recent", @"play"];
    [self.view addSubview:self.segmentedControl];
    [self.view addSubview:self.tableView];
    
    _segmentedControl.selectedSegmentIndex = 0;
    [self initData];
    [self.view addSubview:self.progressView];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
}

//-(void)viewWillDisappear:(BOOL)animated
//{
//    [PlayerButton shareButton].hidden = YES;
//}

#pragma mark - 初始化数据
-(void)initData
{
    _dataSource = [NSMutableArray array];
    [AFTools getDataByURLString:[NSString stringWithFormat:ALLURLString, _searchString] WithDataBlock:^(id data) {
        //专辑数组
        NSMutableArray *albumArray = [NSMutableArray array];
        for (NSDictionary *each in [[data objectForKey:@"album"] objectForKey:@"docs"]) {
            FSearchAlbumModel *model = [[FSearchAlbumModel alloc] init];
            [model setValuesForKeysWithDictionary:each];
            [albumArray addObject:model];
           
        }
        
        //音乐数组
        NSMutableArray *trackArray = [NSMutableArray array];
        for (NSDictionary *each in [[data objectForKey:@"track"] objectForKey:@"docs"]) {
            FSearchMusicModel *model = [[FSearchMusicModel alloc] init];
            [model setValuesForKeysWithDictionary:each];
            [trackArray addObject:model];
        }
        [_dataSource addObject:albumArray];
        [_dataSource addObject:trackArray];
        [_tableView reloadData];
        [_progressView removeFromSuperview];
    }];
}

-(void)initAlbumData:(NSString *)byType
{
    _albumArray = [NSMutableArray array];
    [AFTools getDataByURLString:[NSString stringWithFormat:_urlString, byType, _searchString] WithDataBlock:^(id data) {
        for (NSDictionary *each in [[data objectForKey:@"response"] objectForKey:@"docs"]) {
            FSearchAlbumModel *model = [[FSearchAlbumModel alloc] init];
            [model setValuesForKeysWithDictionary:each];
            [_albumArray addObject:model];
        }
        [self.tableView reloadData];
        [_progressView removeFromSuperview];
    }];
}

-(void)initMusicData:(NSString *)byType
{
    _musicArray = [NSMutableArray array];
    [AFTools getDataByURLString:[NSString stringWithFormat:MusicURLString, byType, _searchString] WithDataBlock:^(id data) {
        for (NSDictionary *each in [[data objectForKey:@"response"] objectForKey:@"docs"]) {
            FSearchMusicModel *model = [[FSearchMusicModel alloc] init];
            [model setValuesForKeysWithDictionary:each];
            [_musicArray addObject:model];
        }
        [self.tableView reloadData];
        [_progressView removeFromSuperview];
    }];
}

#pragma mark - tableView代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_segmentedControl.selectedSegmentIndex == 0) {
        return 2;
    }
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (_segmentedControl.selectedSegmentIndex) {
        case 0:
            if (_dataSource.count == 0) {
                return 0;
            }
            if (section == 0) {
                return [_dataSource[0] count];
            }
            else{
                return [_dataSource[1] count];
            }
            break;
        case 1:
            return _albumArray.count;
            break;
        case 2:
            return _musicArray.count;
            break;
            
        default:
            return 1;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (_segmentedControl.selectedSegmentIndex) {
        case 0:{
            if (indexPath.section == 0) {
                static NSString *album = @"album";
                WWContentTableCell *albumCell = [tableView dequeueReusableCellWithIdentifier:album];
                if (!albumCell) {
                    albumCell = [[WWContentTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:album];
                }
                if (_dataSource.count != 0) {
                    albumCell.searchModel = _dataSource[0][indexPath.row];
                }
                return albumCell;
                break;
            }
            else{
                static NSString *music = @"music";
                FTableViewCell *musicCell = [tableView dequeueReusableCellWithIdentifier:music];
                if (!musicCell) {
                    musicCell = [[FTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:music];
                }
                musicCell.types = FTableViewCellTypeList;
                if (_dataSource.count != 0) {
                    
                    FSearchMusicModel *detail = _dataSource[1][indexPath.row];
                    [musicCell.mainImageView sd_setImageWithURL:[NSURL URLWithString:detail.cover_path] placeholderImage:[UIImage imageNamed:@"placeholderZh"]];
                    musicCell.titleLabel.text = detail.title;
                    musicCell.byLabel.text = detail.nickname;
                    musicCell.timeLabel.text = [NSString stringWithFormat:@"%@", [detail duration]];
                    musicCell.countLabel.text = [NSString stringWithFormat:@"%@", [detail count_play]];
                    //下载block
                    musicCell.block = ^(){
                        
                    };
                }
                
                return musicCell;
                break;
            }
        }
        case 1:{
            static NSString *identifier = @"album";
            WWContentTableCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[WWContentTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.searchModel = _albumArray[indexPath.row];
            return cell;
            break;
        }
        case 2:{
            static NSString *identifier = @"music";
            FTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[FTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
                
            }
            cell.types = FTableViewCellTypeList;
            FSearchMusicModel *detail = _musicArray[indexPath.row];
            [cell.mainImageView sd_setImageWithURL:[NSURL URLWithString:detail.cover_path] placeholderImage:[UIImage imageNamed:@"placeholderZh"]];
            cell.titleLabel.text = detail.title;
            cell.byLabel.text = detail.nickname;
            cell.timeLabel.text = [NSString stringWithFormat:@"%@", [detail duration]];
            cell.countLabel.text = [NSString stringWithFormat:@"%@", [detail count_play]];
            //下载block
            cell.block = ^(){
                
            };
            return cell;
            break;
        }
            
        default:
        {
            static NSString *identifier = @"cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.textLabel.text = @"你好";
            return cell;
            break;
        }
            break;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, FitConstant_YorHeight(40))];
    [view NightWithType:UIViewColorType3];
    UILabel *label = [[UILabel alloc] initWithFrame:FitRectMake(20, 0, 100, 40)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:FitRectMake(5, 10, 20, 20)];
    imageView.image = [UIImage imageNamed:@"sanjiao"];
    if (section == 0) {
        label.text = @" 专辑";
    }
    else{
        label.text = @" 声音";
    }
    [view addSubview:label];
    [view addSubview:imageView];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_segmentedControl.selectedSegmentIndex == 0) {
        return 40;
    }
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (_segmentedControl.selectedSegmentIndex) {
        case 0:{
            if (indexPath.section == 0) {
                AlbumFViewController *vc = [[AlbumFViewController alloc] init];
                FSearchAlbumModel *detail = _dataSource[0][indexPath.row];
                vc.alumbTitel = [NSString stringWithFormat:@"%@", detail.title];
                vc.albumId = [NSString stringWithFormat:@"%@", detail.albumId];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else{
                FPlayViewController *vc = [[FPlayViewController alloc] init];
                FSearchMusicModel *detail = _dataSource[1][indexPath.row];
                vc.trackID = [NSString stringWithFormat:@"%@", detail.TrackId];
                vc.trackUid = [NSString stringWithFormat:@"%@", detail.uid];
                vc.albumId = [NSString stringWithFormat:@"%@", detail.album_id];
                [self.navigationController pushViewController:vc animated:YES];
            }
            break;
        }
        case 1:{
            AlbumFViewController *vc = [[AlbumFViewController alloc] init];
            FSearchAlbumModel *detail = _albumArray[indexPath.row];
            vc.alumbTitel = [NSString stringWithFormat:@"%@", detail.title];
            vc.albumId = [NSString stringWithFormat:@"%@", detail.albumId];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
        case 2:{
            FPlayViewController *vc = [[FPlayViewController alloc] init];
            FSearchMusicModel *detail = _musicArray[indexPath.row];
            vc.trackID = [NSString stringWithFormat:@"%@", detail.TrackId];
            vc.trackUid = [NSString stringWithFormat:@"%@", detail.uid];
            vc.albumId = [NSString stringWithFormat:@"%@", detail.album_id];
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
            
        default:
            break;
    }
}


@end
